import { login, userInfo, userInfoPhoto } from "@/api/user";
import { resetRouter } from "@/router";
import {
  getToken,
  setToken,
  removeToken,
  setTimeDate,
  removeTimeDate
} from "@/utils/auth";

const state = {
  // 保存token
  token: getToken(),
  userInfo: {}
};

const mutations = {
  setTokenL(state, token) {
    // 存到vuex的state
    state.token = token;
    // 存到本地
    setToken(token);
    setTimeDate();
  },
  // 获取用户信息
  setUserInfo(state, payload) {
    state.userInfo = payload;
  },
  // 删除token
  removeToken(state) {
    state.token = null;
    removeToken();
    removeTimeDate();
    resetRouter();
  },
  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = {};
  }
};
const actions = {
  // 发请求获取token
  async login(context, payload) {
    // 传入参数
    try {
      let res = await login(payload);
      context.commit("setTokenL", res.data);
    } catch (error) {
      // 来到这证明请求失败，让代码报错
      // 这样子Login.vue就能收到失败的信息了
      return Promise.reject(error);
    }
  },
  // 获取用户信息
  async getUserInfo(context) {
    let res = await userInfo();
    let res2 = await userInfoPhoto(res.data.userId);
    let allRes = {
      ...res.data,
      ...res2.data
    };
    // console.log(allRes);
    context.commit("setUserInfo", allRes);

    return allRes;
  },
  // 退出登录
  logout({ commit, dispatch }) {
    commit("removeToken");
    commit("removeUserInfo");
    resetRouter();
    dispatch("tagsView/delAllViews", null, { root: true });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
